<template>
  <div class="in">
    <div class="tit">
      <div class="ul1">
        <div :class="{sta:ind==0}"
             @click="stab(0)">基本信息</div>
        <div :class="{sta:ind==1}"
             @click="stab(1)">修改密码</div>
        <div :class="{sta:ind==2}"
             v-if="level"
             @click="stab(2)">采购人</div>
      </div>
      <div class="ul2"
           v-if="level"
           @click="addUser">创建账户</div>
    </div>
    <!-- 基本信息 -->
    <div v-if="ind==0"
         class="qie">
      <div v-if="userInfoForm.level=='2'">
        <el-form label-position="right"
                 label-width="100px"
                 :model="userInfoForm">
          <el-form-item label="头像："
                        class="a">
            <el-avatar class="img"
                       :src="userInfoForm.avator"
                       v-loading="isHeadSuccess"
                       @error="true">
              <img :src="errorHeadImg">
            </el-avatar>
            <el-upload :action="baseurl+'/api/common/upload'"
                       list-type="picture-card"
                       :on-progress="progress"
                       :before-upload="beforeUpload"
                       :limit="1"
                       :show-file-list='false'
                       :on-success="uploadSuccess"
                       :accept="'image/*'"
                       :multiple="false"
                       ref="my-upload"
                       class="b">
              <span>点击可修改</span>
            </el-upload>
          </el-form-item>
          <el-form-item label="会员类型：">
            <el-input v-model="this.$store.getters.getuser.levelText"
                      :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input v-model="userInfoForm.name"></el-input> <span class="span">点击可修改</span>
          </el-form-item>
          <el-form-item label="绑定手机号：">
            <el-input v-model="ipo"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="性别：">
            <el-radio-group v-model="userInfoForm.sex">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="企业名称"
                        :required="true">
            <el-input v-model="userInfoForm.qname"
                      placeholder="请输入企业名称"></el-input>
          </el-form-item>
          <el-form-item label="企业网址"
                        :required="true">
            <el-input v-model="userInfoForm.website"
                      placeholder="请输入企业网址"></el-input>
          </el-form-item>
          <el-form-item label="企业位置"
                        :required="true">
            <el-input v-model="userInfoForm.address"
                      placeholder="请输入企业位置"></el-input>
          </el-form-item>
          <el-form-item label="公司资质："
                        class="a">
            <el-avatar class="img"
                       :src="userInfoForm.imgurl"
                       v-loading="isHeadSuccess1"
                       @error="true">
              <img :src="errorHeadImg">
            </el-avatar>
            <el-upload :action="baseurl+'/api/common/upload'"
                       list-type="picture-card"
                       :on-progress="progress1"
                       :before-upload="beforeUpload"
                       :limit="1"
                       :show-file-list='false'
                       :on-success="uploadSuccess1"
                       :accept="'image/*'"
                       :multiple="false"
                       ref="my-upload1"
                       class="b">
              <span>点击可修改</span>
            </el-upload>
          </el-form-item>
        </el-form>
        <div class="sub"
             @click="resetSubmit1()">提交</div>
      </div>
      <div v-else>
        <el-form label-position="right"
                 label-width="100px"
                 :model="userInfoForm">
          <el-form-item label="头像："
                        class="a">
            <el-avatar class="img"
                       :src="userInfoForm.avator"
                       v-loading="isHeadSuccess"
                       @error="true">
              <img :src="errorHeadImg">
            </el-avatar>
            <el-upload :action="baseurl+'/api/common/upload'"
                       list-type="picture-card"
                       :on-progress="progress"
                       :before-upload="beforeUpload"
                       :limit="1"
                       :show-file-list='false'
                       :on-success="uploadSuccess"
                       :accept="'image/*'"
                       :multiple="false"
                       ref="my-upload"
                       class="b">
              <span>点击可修改</span>
            </el-upload>
          </el-form-item>
          <el-form-item label="会员类型：">
            <el-input v-model="this.$store.getters.getuser.levelText"
                      :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input v-model="userInfoForm.name"></el-input> <span class="span">点击可修改</span>
          </el-form-item>
          <!-- v-model="this.$store.getters.getuser.phone" -->
          <el-form-item label="绑定手机号：">
            <el-input v-model="ipo"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="性别：">
            <el-radio-group v-model="userInfoForm.sex">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="sub"
             @click="resetSubmit()">提交</div>
      </div>

    </div>
    <!-- 修改密码 -->
    <div v-if="ind==1"
         class="qie">
      <el-form label-position="right"
               label-width="100px"
               :model="setPasForm">
        <el-form-item label="手机号：">
          <!-- <el-input v-model="setPasForm.phone"
                    placeholder="请输入您的手机号"></el-input> -->
          <el-input v-model="this.ipo"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="旧密码：">
          <el-input v-model="setPasForm.oldPassword"
                    type="password"
                    placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码：">
          <el-input v-model="setPasForm.newPassword"
                    placeholder="请输入长度不大于15的新密码"
                    type="password"
                    maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：">
          <el-input v-model="setPasForm.rNewPassword"
                    placeholder="请确认密码"
                    type="password"
                    maxlength="15"></el-input>
        </el-form-item>
        <!-- <el-form-item class="ma"
                      label="验证码：">
          <el-input v-model="setPasForm.ma"
                    placeholder="请输入验证码"></el-input>
          <div class="daoji"
               @click="getCode"
               :class="{code:!show}">
            <span v-show="show">获取验证码</span>
            <span v-show="!show"
                  class="count">{{ count }} s</span>
          </div>
        </el-form-item> -->
      </el-form>
      <div class="sub"
           @click="rsetPasSub">提交</div>
    </div>
    <!-- 采购人 -->
    <div v-if="ind==2"
         class="qie">
      <div class="cai"
           v-if="table">
        <el-table :data="table"
                  style="width: 100%">
          <el-table-column type="index">
          </el-table-column>
          <el-table-column prop="name"
                           label="姓名"
                           align="center">
          </el-table-column>
          <el-table-column prop="level"
                           label="级别"
                           align="center">
          </el-table-column>
          <el-table-column prop="upName"
                           label="上级"
                           align="center">
          </el-table-column>
          <el-table-column prop="phone"
                           label="手机号"
                           align="center">
          </el-table-column>
          <el-table-column prop="caAt"
                           label="创建时间"
                           align="center">
          </el-table-column>
          <el-table-column prop="caozuo"
                           label="操作"
                           width="250"
                           align="center">
            <template slot-scope="scope">
              <el-button size="mini"
                         @click="handleEdit(scope.row.companyUserId)">编辑</el-button>
              <el-button size="mini"
                         @click="rsetPasPop(scope.row.companyUserId)">修改密码</el-button>
              <el-button size="mini"
                         type="danger"
                         @click="handleDelete(scope.row.companyUserId)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <el-pagination background
                       layout="prev, pager, next"
                       :total="total"
                       @current-change="changePage"
                       prev-text="上一页"
                       next-text="下一页"
                       :current-page.sync="page"
                       :page-size="pageSize"
                       class="aut">
        </el-pagination>

      </div>
      <div v-else>暂无采购人</div>
    </div>
    <el-dialog title="新增/修改账户"
               :visible.sync="dialog"
               class="dialog">
      <el-form :model="form2"
               label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="form2.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form2.phone"
                    :disabled="isDisabled"></el-input>
        </el-form-item>
        <el-form-item label="选择上级">
          <el-select v-model="form2.parentId"
                     placeholder="请选择上级">
            <el-option v-for="item in upUserList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="级别">
          <el-select v-model="form2.level"
                     placeholder="请选择级别">
            <el-option label="采购员"
                       value="1"></el-option>
            <el-option label="审核员"
                       value="2"></el-option>
            <el-option label="复核员"
                       value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码"
                      v-if="isAdd">
          <el-input type="password"
                    v-model="form2.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="openUserSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改密码"
               :visible.sync="rsetPasDialog"
               class="dialog">
      <el-form label-width="80px">
        <el-form-item label="新密码"
                      v-if="isAdd">
          <el-input v-model="newPasW"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="rsetPasDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="pasSubmit">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      baseurl: "",
      ind: 0,
      errorHeadImg: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      userInfoForm: {}, // 用户基本信息表单
      isHeadSuccess: false, // 头像是否上传完成
      isHeadSuccess1: false, // 头像是否上传完成
      setPasForm: { // 修改密码表单
        phone: "",
        oldPassword: "",
        newPassword: "",
        rNewPassword: ""
      },
      show: true,
      count: "", //倒计时时间
      timer: null, //倒计时事件
      table: [], // 采购人表单
      dialog: false,
      isAdd: true,
      form2: {
        name: '',
        phone: '',
        parentId: "", // 上级id
        level: '',
        password: ''
      },
      upUserList: [], // 上级列表
      total: 0,
      page: 1,
      pageSize: 10,
      rsetPasDialog: false,
      paswId: "", // 修改密码的id
      newPasW: "",
      isDisabled: false,
      resetUserId: "",// 被修改的用户id
      level: false,//企业管理者
      ipo: '',
    }
  },
  created() {
    this.baseurl = this.$baseUrl;
  },
  mounted() {
    this.getUserInfo();
    this.getUserList();
    this.ipo1()
    // this.ipo = this.$store.getters.getuser.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')

    // console.log(this.$store.getters.getuser.phone.this.$store.getters.getuser.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'))
  },
  methods: {
    ipo1() {
      this.ipo = this.$store.getters.getuser.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    },
    stab(i) {
      this.ind = i
    },
    beforeUpload(file) {
      // 判断图片是否大于2M
      const isLt2M = file.size / 1024 / 1024 < 2;
      // const fileType = file.name.substring(file.name.lastIndexOf('.')+1)
      // 判断图片的类型
      const isJpg =
        file.type == "image/jpeg" ||
        file.type == "image/jpg" ||
        file.type == "image/png" ||
        file.type == "image/gif";
      if (!isJpg) {
        this.$message.error("只能上传jpg, jpeg, png, gif格式的图片！");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
    },
    progress() {
      this.isHeadSuccess = true;
    },
    progress1() {
      this.isHeadSuccess1 = true;
    },
    uploadSuccess(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.userInfoForm.avator = res.data;
      this.isHeadSuccess = false;
      this.$refs['my-upload'].clearFiles();
    },
    uploadSuccess1(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.userInfoForm.imgurl = res.data;
      this.isHeadSuccess1 = false;
      this.$refs['my-upload1'].clearFiles();
    },
    getCode() {
      if (!this.show) return;
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    // 获取用户信息
    getUserInfo() {
      const that = this;
      this.$postRequest("/api/user/getUserInfo", {
        userId: localStorage.getItem("userId")
      }).then(res => {
        // that.userInfo = res.data;
        if (res.data.level == 0) {
          res.data.levelText = "普通用户"
        } else if (res.data.level == 1) {
          res.data.levelText = "商家"
        } else if (res.data.level == 2) {
          res.data.levelText = "企业用户"
          res.data.qname = res.data.mallCompanyUserDO.name
          res.data.website = res.data.mallCompanyUserDO.website
          res.data.address = res.data.mallCompanyUserDO.address
          res.data.imgurl = res.data.mallCompanyUserDO.imgurl
          this.level = res.data.mallCompanyUserDO.level == 0
        }
        that.userInfoForm = res.data;
      })
    },
    // 修改用户信息
    resetSubmit() {
      if (this.userInfoForm.name == "") {
        this.$message.error("请输入昵称")
      } else {
        const that = this;
        this.$postRequest("/api/user/updateUser", {
          userId: localStorage.getItem("userId"),
          avator: this.userInfoForm.avator,
          name: this.userInfoForm.name,
          sex: this.userInfoForm.sex
        }).then(res => {
          that.$message.success("修改成功");
          that.$store.commit("setUser", that.userInfoForm);
        })
      }
    },
    resetSubmit1() {
      if (this.userInfoForm.name == "") {
        this.$message.error("请输入昵称")
      } else if (!this.userInfoForm.qname) {
        this.$message.error("请输入公司名称")
      } else if (!this.userInfoForm.website) {
        this.$message.error("请输入公司网址")
      } else if (!this.userInfoForm.address) {
        this.$message.error("请输入公司位置")
      } else if (!this.userInfoForm.imgurl) {
        this.$message.error("请上传公司资质")
      } else {
        const that = this;
        this.$postRequest("/api/user/completionCompanyUser", {
          userId: localStorage.getItem("userId"),
          avator: this.userInfoForm.avator,
          userName: this.userInfoForm.name,
          sex: this.userInfoForm.sex,
          name: this.userInfoForm.qname,
          website: this.userInfoForm.website,
          address: this.userInfoForm.address,
          imgurl: this.userInfoForm.imgurl,
        }).then(res => {
          that.$message.success("修改成功");
          that.$store.commit("setUser", that.userInfoForm);
        })
      }
    },
    // 修改密码提交
    rsetPasSub() {
      var value = this.setPasForm;
      if (value.newPassword == "" || value.oldPassword == "" || value.rNewPassword == "") {
        this.$message.error("内容不允许有空，请填写完整")
      } else if (value.newPassword != value.rNewPassword) {
        this.$message.error("两次新密码输入不一致，请重新输入")
      } else {
        const that = this;
        this.$postRequest("/api/user/updateUserPassword", {
          userId: localStorage.getItem("userId"),
          oldPassword: value.oldPassword,
          newPassword: value.newPassword,
          phone: this.$store.getters.getuser.phone
        }).then(res => {
          that.$message.success("修改成功");
          value.oldPassword = "";
          value.newPassword = "";
          value.rNewPassword = "";
        })
      }
    },
    // 获取采购人列表
    getUserList() {
      const that = this;
      this.$postRequest("/api/user/getCompanyUserList", {
        userId: localStorage.getItem("userId"),
        pageSize: this.pageSize,
        pageNum: this.page
      }).then(res => {
        that.total = res.data.total;
        for (var i = 0; i < res.data.list.length; i++) {
          if (res.data.list[i].level == 1) {
            res.data.list[i].level = "采购员"
          } else if (res.data.list[i].level == 2) {
            res.data.list[i].level = "审核员"
          } else if (res.data.list[i].level == 3) {
            res.data.list[i].level = "复核员"
          }
        }
        that.table = res.data.list;
      })
    },
    // 删除采购人
    handleDelete(id) {
      // console.log(id)
      const that = this;
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.$postRequest("/api/user/deleteCompanyUser", {
          companyUserId: id
        }).then(res => {
          that.$message.success("删除成功");
          that.getUserList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    // 获取上级列表
    getUpUser() {
      const that = this;
      this.$postRequest("/api/user/getUpUser", {
        userId: localStorage.getItem("userId")
      }).then(res => {
        that.upUserList = res.data;
      })
    },
    // 采购人创建弹框
    addUser() {
      this.dialog = true;
      this.isAdd = true;
      this.isDisabled = false;
      this.getUpUser();
      this.clearForm2();
    },
    // 采购人编辑弹框
    handleEdit(id) {
      this.getUpUser();
      this.dialog = true
      this.isAdd = false;
      const that = this;
      this.isDisabled = true;
      this.$postRequest("/api/user/getCompanyUserInfo", {
        companyUserId: id
      }).then(res => {
        if (res.data.level == 1) {
          res.data.level = "采购员"
        } else if (res.data.level == 2) {
          res.data.level = "审核员"
        } else if (res.data.level == 3) {
          res.data.level = "复核员"
        }
        that.resetUserId = res.data.companyUserId;
        that.form2 = res.data;
      })
    },
    // 弹框确认
    openUserSubmit() {
      var value = this.form2;
      var phoneReg = /^1[0-9]{10}$/;
      if (value.name == "" || value.level == "" || value.parentId == "" || value.phone == "") {
        this.$message.error("请将内容补充完整")
      } else if (!phoneReg.test(value.phone)) {
        this.$message.error("手机号错误，请检查后重新提交")
      } else {
        if (this.isAdd) {
          this.addUserSubmit();
        } else {
          this.editUserSubmit();
        }
      }
    },
    // 新增采购人提交
    addUserSubmit() {
      console.log("新增")
      if (this.form2.password == "") {
        this.$message.error("请填写密码");
      } else {
        console.log(this.form2);
        const that = this;
        this.$postRequest("/api/user/addCompanyUser", {
          userId: localStorage.getItem("userId"),
          name: this.form2.name,
          phone: this.form2.phone,
          password: this.form2.password,
          parentId: this.form2.parentId,
          level: this.form2.level,
        }).then(res => {
          that.$message.success("添加成功");
          that.dialog = false;
          that.getUserList();
        })
      }
    },
    // 修改采购人提交
    editUserSubmit() {
      const that = this;
      var level = 0;
      if (this.form2.level == "采购员") {
        level = 1
      } else if (this.form2.level == "审核员") {
        level = 2
      } else if (this.form2.level == "复核员") {
        level = 3
      }
      this.$postRequest("/api/user/updateCompanyUserInfo", {
        companyUserId: this.resetUserId,
        name: this.form2.name,
        parentId: this.form2.parentId,
        level: level,
      }).then(res => {
        that.$message.success("修改成功");
        that.dialog = false;
        that.getUserList();
      })
    },
    // 清空采购人弹框
    clearForm2() {
      this.form2 = {
        name: '',
        phone: '',
        parentId: "",
        level: '',
        password: ''
      };
    },
    // 打开修改密码弹框
    rsetPasPop(id) {
      this.newPasW = "";
      this.rsetPasDialog = true;
      this.paswId = id;
    },
    // 提交新密码
    pasSubmit() {
      if (this.newPasW == "") {
        this.$message.error("请输入新密码")
      } else {
        const that = this;
        this.$postRequest("/api/user/updateCompanyUserPassword", {
          companyUserId: this.paswId,
          password: this.newPasW
        }).then(res => {
          that.$message.success("修改成功");
          that.rsetPasDialog = false;
        })
      }
    },
    // 采购人分页
    changePage(val) {
      this.page = val;
      this.getUserList();
    }
  }
}
</script>
<style scoped lang="scss">
.aut {
  text-align: center;
  margin-top: 14px;
  margin-bottom: 14px;
}
.in {
  width: 100%;
  // height: 840px;
  background: #ffffff;
  border: 1px solid #eeeeee;
  .tit {
    width: 100%;
    height: 50px;
    background: #ffffff;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .ul1 {
      display: flex;
      height: 100%;
      align-items: center;
      div {
        width: 100px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #000000;
        cursor: pointer;
        &.sta {
          color: #1a69e0;
          position: relative;
          &::after {
            content: '';
            width: 100px;
            height: 2px;
            background: #1a69e0;
            position: absolute;
            bottom: 0;
            left: 0;
          }
        }
      }
    }
    .ul2 {
      padding-right: 20px;
      cursor: pointer;
      color: #1a69e0;
      &:hover {
        opacity: 0.8;
      }
    }
  }
  .qie {
    width: 100%;
    padding: 30px 20px;
    /deep/ .el-input {
      width: 500px;
    }
    .ma {
      /deep/ .el-input {
        width: 380px;
      }
      /deep/ .el-form-item__content {
        display: flex;
      }
      .daoji {
        width: 100px;
        height: 40px;
        background: rgba(26, 105, 224, 0.05);
        border: 1px solid #1a69e0;
        text-align: center;
        line-height: 40px;
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #1a69e0;
        margin-left: 20px;
        cursor: pointer;
        &.code {
          border: 1px solid #eeeeee;
          background: #eeeeee;
          color: #999999;
        }
      }
    }
    .span {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
      margin-left: 20px;
    }
    .img {
      width: 70px;
      height: 70px;
      vertical-align: middle;
    }
    .a {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
      /deep/ .el-form-item__label {
        margin-top: 20px;
      }

      span {
        margin-left: 20px;
        cursor: pointer;
      }
      .b {
        width: 100px;
        display: inline-block;
        /deep/ .el-upload--picture-card {
          background-color: #ffffff;
          border: none;
          border-radius: 0px;
          box-sizing: border-box;
          width: 100px;
          height: 30px;
          line-height: 30px;
          vertical-align: baseline;
        }
      }
    }
    .sub {
      width: 100px;
      height: 35px;
      line-height: 35px;
      background: #1a69e0;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffffff;
      text-align: center;
      margin: 120px 180px;
      cursor: pointer;
      &:hover {
        opacity: 0.8;
      }
    }
    .cai {
      width: 100%;
      background: #ffffff;
      border: 1px solid #eeeeee;
      border-bottom: none;
    }
  }
  /deep/ .el-select {
    width: 100%;
  }
  /deep/ .el-avatar > img {
    width: 100%;
  }
  /deep/ .el-input.is-disabled .el-input__inner {
    color: #333;
  }
  /deep/ .el-radio__input.is-checked .el-radio__inner {
    border-color: #1a69e0;
    background: #1a69e0;
  }
  /deep/ .el-radio__input.is-checked + .el-radio__label {
    color: #1a69e0;
  }
}
</style>